function Engine() {
	var me = this;
	
	var builds;
	var currentBuildIndex;

	me.builds = [];
	me.currentBuildIndex = 0;
	me.Events = {
		'currentbuildchanged' : [],
		'buildadded' : [],
		'builddeleted' : []
	};
}

Engine.prototype = new Event();

Engine.prototype.addBuild = function(data) {
	var me = this;
	var newBuild = new Build();
	
	if (data) {
		newBuild.init(data);
	}
	newBuild.on('changed', function(build) {
		me.save();
	});
	me.builds.push(newBuild);
	me.broadcast('buildadded', newBuild, me.builds.length - 1);
	if (me.builds.length == 1) {
		me.broadcast('currentbuildchanged', 0);
	}
	me.save();
	return newBuild;
};

Engine.prototype.deleteBuild = function(index) {
	var me = this;
	
	if (index >= 0 && index < me.builds.length) {
		var newArray = [];
		for (var i = 0; i < index; ++i) {
			newArray.push(me.builds[i]);
		}
		i++;
		for (; i < me.builds.length; ++i) {
			newArray.push(me.builds[i]);
		}
		me.builds = newArray;
		me.save();
		/* if (index == me.currentBuildIndex) {
			me.currentBuildIndex = 0;
			me.broadcast('selectedbuildchanged');
		} else if (index < me.currentBuildIndex) {
			me.currentBuildIndex--;
			me.broadcast('selectedbuildchanged');
		} */
		me.currentBuildIndex--;
		if (me.currentBuildIndex < 0)
			me.currentBuildIndex = 0;
		me.broadcast('currentbuildchanged', me.currentBuildIndex);
	}
};

Engine.prototype.getBuild = function(index) {
	var me = this;
	
	if (index >= 0 && index < me.builds.length)
		return me.builds[index];
};

Engine.prototype.getCurrentBuild = function() {
	var me = this;
	
	return me.builds[me.currentBuildIndex];
};

Engine.prototype.init = function() {
	var me = this;
	var data = localStorage['builds'];
	
	if (!data || data == '' || JSON.parse(data).length == 0) {
		me.addBuild();
	} else {
		var dataBuilds = JSON.parse(data);
		
		for (var i = 0; i < dataBuilds.length; ++i) {
			me.addBuild(dataBuilds[i]);
		}
	}
	
	me.broadcast('currentbuildchanged', 0);
};

Engine.prototype.save = function() {
	var me = this;
	var buildsData = [];
	
	for (var i = 0; i < me.builds.length; ++i) {
		buildsData.push(me.builds[i].data);
	}
	
	var s = JSON.stringify(buildsData);
	
	console.log('Saved.');
	console.log(buildsData);
	
	localStorage['builds'] = s;
};

Engine.prototype.setCurrentBuild = function(index) {
	var me = this;
	
	if (index >= 0 && index < me.builds.length) {
		me.currentBuildIndex = index;
		me.broadcast('currentbuildchanged', index);
	}
};
